package com.rzico.sbl.ui.statistic

import android.view.inputmethod.EditorInfo
import android.widget.ImageView
import androidx.core.view.isGone
import androidx.core.view.isVisible
import androidx.core.widget.doOnTextChanged
import com.jeremyliao.liveeventbus.utils.observe
import com.rzico.sbl.R
import com.rzico.sbl.databinding.ActivityStockGoodsBinding
import com.rzico.sbl.model.BaseUrl
import com.rzico.sbl.model.FilterData
import com.rzico.sbl.model.StockGoods
import com.rzico.sbl.other.showStockDialog
import com.rzico.sbl.ui.goods.GoodsActivity
import com.rzico.sbl.viewmodel.StatisticStockViewModel
import com.xinnuo.common.decoration.SpaceTBDecoration
import com.xinnuo.common.extend.*
import com.xinnuo.common.helper.bottomHide
import com.xinnuo.common.helper.bottomShow
import com.xinnuo.common.helper.hideSoftInput
import com.xinnuo.common.helper.intValue
import com.xinnuo.common_ui.base.BaseActivity
import com.xinnuo.common_ui.base.addItems
import com.xinnuo.common_ui.base.loadLinear
import com.xinnuo.common_ui.glideExt.loadImage
import com.xinnuo.common_ui.utils.addOnScrollChanged
import com.xinnuo.common_ui.utils.bindLifeCycle
import com.xinnuo.common_ui.utils.showHintDialog
import com.xinnuo.common_ui.utils.showListDialog
import com.xinnuo.common_ui.utils.subscribeBySuccess
import com.xinnuo.slimadapter.SlimAdapter

class StockGoodsActivity : BaseActivity(R.layout.activity_stock_goods) {

    private val mBinding by lazy { ActivityStockGoodsBinding.bind(getRootView()) }

    private val mShopList = arrayListOf<FilterData>()
    private var mKeyWord = ""
    private var mShopId = ""

    override fun getViewModel() = get<StatisticStockViewModel>()

    override fun initData() {
        setToolbarVisibility(isVisible = false)

        initLayout()
        initSearch()

        getShopList()
    }

    private fun initLayout() {
        mBinding
            .listLayout
            .apply {
                emptyLayout
                    .emptyHint
                    .text = "暂无相关商品信息！"

                recycleList.also { layout ->
                    layout.loadLinear(
                        refresh = swipeRefresh,
                        onRefresh = { getData(0) },
                        onLoad = {
                            isLoadingMore
                                .conditionFalse {
                                    isLoadingMore = true
                                    getData(pageNum)
                                }
                        }
                    )

                    layout.addItemDecoration(SpaceTBDecoration(hasHeader = false, bottom = 60f))
                    layout.addOnScrollChanged(
                        onShow = { mBinding.goodsBottom.bottomShow() },
                        onHide = { mBinding.goodsBottom.bottomHide(55f) }
                    )

                    mAdapter = SlimAdapter.creator()
                        .register<StockGoods>(R.layout.item_stock_goods) { jector, bean, index ->
                            jector.apply {
                                text(R.id.item_stock_name, bean.name)
                                text(R.id.item_stock_code, bean.sn)
                                text(R.id.item_stock_group, bean.mapProductCategory?.name.orEmpty())
                                text(R.id.item_stock_stock, bean.stock)

                                visibility(
                                    R.id.item_stock_jian,
                                    goneValue { bean.stock.intValue == 0 }
                                )

                                with<ImageView>(R.id.item_stock_img) {
                                    it.loadImage(bean.thumbnail)
                                }

                                clicked(R.id.item_stock_jian) {
                                    decreaseStock(bean.id, bean.name)
                                }

                                clicked(R.id.item_stock_jia) {
                                    increaseStock(bean.id, bean.name)
                                }

                                clicked {
                                    startActivityEx<StockRecordActivity>(
                                        "stockId" to bean.id
                                    )
                                }

                                longClicked {
                                    deleteGoods(bean.id, index)
                                    true
                                }
                            }
                        }
                        .attachTo(layout)
                }
            }
    }

    private fun initSearch() {
        mBinding
            .goodsSearch
            .apply {
                searchEdit.hint = "请输入商品名称"
                searchEdit.doOnTextChanged { text, _, _, _ ->
                    text?.let {
                        searchClose.isGone = it.isEmpty()

                        (it.isEmpty() && mKeyWord.isNotEmpty())
                            .condition {
                                mKeyWord = ""
                                updateList()
                            }
                    }
                }

                searchEdit.setOnEditorActionListener { _, actionId, _ ->
                    (actionId == EditorInfo.IME_ACTION_SEARCH)
                        .condition {
                            hideSoftInput() //隐藏软键盘

                            searchEdit.text
                                .isBlank()
                                .conditionElse(
                                    actionTrue = { showToast("请输入商品名称") },
                                    actionFalse = {
                                        mKeyWord = searchEdit.textTrim
                                        updateList()
                                    }
                                )
                        }
                    return@setOnEditorActionListener false
                }

                searchClose.oneClick { searchEdit.setText("") }
                searchHint.oneClick {
                    searchEdit.text
                        .isBlank()
                        .conditionElse(
                            actionTrue = { showToast("请输入商品名称") },
                            actionFalse = {
                                mKeyWord = searchEdit.textTrim
                                updateList()
                            }
                        )
                }
            }
    }

    override fun initListener() {
        mBinding
            .btAdd
            .oneClick {
                startActivityEx<GoodsActivity>(
                    "mode" to "multiple",
                    "hint" to "请选择要添加的商品"
                )
            }

        mBinding
            .goodsShop
            .apply {
                timeHint.text = "仓库名称"

                timeLayout
                    .oneClick {
                        getViewModel()
                            .showDropFilter(
                                getIContext(),
                                timeLayout,
                                mShopList,
                                timeHint,
                                timeHintArrow,
                            ) { bean ->
                                mShopId = bean.id

                                updateList()
                            }
                    }
            }

        observe<String>("goodsMultiple") {
            getViewModel()
                .delay {
                    getViewModel()
                        .requestBind(
                            requestUrl = BaseUrl.mngPickProA,
                            params = arrayOf(
                                "shopId" to mShopId,
                                "ids" to it
                            )
                        )
                        .bindLifeCycle(getLifecycleOwner())
                        .subscribeBySuccess(
                            event = getViewModel(),
                            onSuccess = {
                                showToast("添加商品成功！")

                                updateList()
                            }
                        )
                }
        }
    }

    /**
     * 增加商品库存
     */
    private fun increaseStock(itemId: String, name: String) {
        showStockDialog(
            name = name,
            type = 1,
            isForced = true,
            onSelect = { view, arr ->
                mPosition = 0

                showListDialog(
                    title = "请选择事由",
                    items = getViewModel().reasonIn(),
                    index = mPosition,
                    listener = { index, hint ->
                        mPosition = index
                        view.text = hint
                        arr[0] = hint
                    }
                )
            },
            onSure = { reason, num, memo ->
                getViewModel()
                    .request(
                        requestUrl = BaseUrl.psiStock,
                        isMultipart = true,
                        params = arrayOf(
                            "id" to itemId,
                            "action" to 0,
                            "quantity" to num,
                            "subject" to reason,
                            "memo" to memo
                        ),
                        onSuccess = {
                            showToast("库存修改成功！")

                            updateList()
                        }
                    )
            }
        )
    }

    /**
     * 减少商品库存
     */
    private fun decreaseStock(itemId: String, name: String) {
        showStockDialog(
            name = name,
            type = 2,
            isForced = true,
            onSelect = { view, arr ->
                mPosition = 0

                showListDialog(
                    title = "请选择事由",
                    items = getViewModel().reasonOut(),
                    index = mPosition,
                    listener = { index, hint ->
                        mPosition = index
                        view.text = hint
                        arr[0] = hint
                    }
                )
            },
            onSure = { reason, num, memo ->
                getViewModel()
                    .request(
                        requestUrl = BaseUrl.psiStock,
                        isMultipart = true,
                        params = arrayOf(
                            "id" to itemId,
                            "action" to 1,
                            "quantity" to num,
                            "subject" to reason,
                            "memo" to memo
                        ),
                        onSuccess = {
                            showToast("库存修改成功！")

                            updateList()
                        }
                    )
            }
        )
    }

    /**
     * 删除商品
     */
    private fun deleteGoods(itemId: String, index: Int) {
        showHintDialog(
            title = "删除商品",
            hint = "确定要删除该商品和库存吗？",
            sure = "删除",
            onSure = {
                getViewModel()
                    .request(
                        requestUrl = BaseUrl.mngPickProD,
                        params = arrayOf("ids" to itemId),
                        onSuccess = {
                            showToast("商品删除成功！")

                            mList.removeAt(index)
                            mAdapter.apply {
                                notifyItemRemoved(index)
                                notifyItemRangeChanged(index, mList.size - index)
                            }

                            mBinding.listLayout
                                .emptyLayout
                                .emptyView
                                .isVisible = mList.isEmpty()
                        }
                    )
            }
        )
    }

    /**
     * 获取店铺列表，含自提点
     */
    private fun getShopList() {
        getViewModel()
            .shopList(
                onSuccess = { list ->
                    mShopList.clear()
                    list.notEmpty {
                        mapTo(mShopList) {
                            FilterData(
                                it.shopName.orEmpty(),
                                it.id,
                                it.shopName.orEmpty()
                            )
                        }
                    }

                    mShopId = mShopList[0].id
                    mShopList[0].isChecked = true

                    mBinding.apply {
                        goodsShop
                            .timeHint
                            .text = mShopList[0].name

                        listLayout
                            .swipeRefresh
                            .isRefreshing = true
                    }
                },
                onFinally = { getData(pageNum) }
            )
    }

    /**
     * 商品列表
     */
    override fun getData(index: Int, isLoading: Boolean) {
        getViewModel()
            .goodsList(
                page = index,
                shopId = mShopId,
                keyWord = mKeyWord,
                onSuccess = {
                    mList.apply {
                        (index == 0)
                            .condition {
                                clear()
                                pageNum = 0
                            }

                        addItems(it.data)
                        it.data.notEmpty { pageNum++ }
                    }

                    mAdapter.setDataList(mList)

                    mBinding.apply {
                        goodsCount.text = it.summary?.subTotal.orEmpty("0")
                        goodsNum.text = it.summary?.subQuantity.orEmpty("0")
                    }
                },
                onFinally = {
                    isLoadingMore = false

                    mBinding
                        .listLayout
                        .apply {
                            swipeRefresh.isRefreshing = false

                            emptyLayout
                                .emptyView
                                .isVisible = mList.isEmpty()
                        }
                }
            )
    }

    /**
     * 刷新列表数据
     */
    private fun updateList() {
        mBinding
            .listLayout
            .apply {
                swipeRefresh.isRefreshing = true

                emptyLayout
                    .emptyView
                    .gone()
            }

        mList.notEmpty {
            clear()
            mAdapter.notifyDataSetChanged()
        }

        getData(0)
    }

}